package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import bean.general.Style;

@ManagedBean
@ApplicationScoped
public class DaoStyle extends Dao {
	private ArrayList<Style> styles;
	
	public ArrayList<Style> getStyles () throws NotFoundException, DaoException {
		styles = new ArrayList<Style>();
		
		ResultSet rs = null;

		String query = 
				"SELECT * " +
						"FROM " + Style.TABLE_NAME;
		;
		try {
			rs = st.executeQuery(query);
			log.log(3, this.getClass() + ". Execution: " + query);
		} catch (SQLException e) {
			throw new DaoException(this.getClass() + ". Error executing query: " + query);
		}

		try {
			int colNum = rs.getMetaData().getColumnCount();
			HashMap<String, String> line;
			Style style;

			while (rs.next()) {
				line = new HashMap <String, String>();
				for (int i = 1; i <= colNum; i++)
				{
					line.put(rs.getMetaData().getColumnLabel(i), rs.getString(i));
				}

				style = new Style(line);
				styles.add(style);
			}

			if (styles.size() == 0)
			{
				throw new NotFoundException(this.getClass() + ". No styles found");
			}
		} catch (SQLException e) {
			throw new DaoException(this.getClass() + ". Error getting styles from Database");
		}

		return styles;
	}

	/**
	 * Get the Style info from database
	 * @param styleName
	 * @return
	 * @throws DaoException 
	 * @throws NotFoundException 
	 */
	public Style getStyle(String styleName) throws DaoException, NotFoundException {
		Style style = null;
		ResultSet rs = null;
		
		String query = 
				"SELECT * " +
						"FROM " + Style.TABLE_NAME + " " +
						"WHERE " + Style.NAME_COL + " = '" + styleName + "' "
				;
		try {
			rs = st.executeQuery(query);
			log.log(3, this.getClass() + ". Execution: " + query);
		} catch (SQLException e) {
			throw new DaoException(this.getClass() + ". Error executing query: " + query);
		}

		try {
			int colNum = rs.getMetaData().getColumnCount();

			if (rs.next()) {
				HashMap<String, String> line = new HashMap <String,String>();
				for (int i = 1; i <= colNum; i++)
				{
					line.put(rs.getMetaData().getColumnLabel(i), rs.getString(i));
				}

				style = new Style(line);
			}
			else
			{
				throw new NotFoundException(this.getClass() + ". No style found with this name");
			}
		} catch (SQLException e) {
			throw new DaoException(this.getClass() + ". Unable to get style " + styleName + " from Database");
		}
		
		return style;
	}
}
